<template>
  <div class="audit-dialog">
    <el-dialog
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      :append-to-body="true"
      :class="[
        content && content.isRichText
          ? 'medium-common-dialog-size'
          : 'auto-common-dialog-size',
        showMobilePage?'mobile-page-dialog':''
      ]"
      @open="opened"
    >
      <template>
        <div>
          <DialogTitle :style="operateData.approvalExplanation || showMobilePage?{marginBottom: '8px'}:{marginBottom: '24px'}" title="审批确认" font-size="16px">
            <el-checkbox v-model="continueApprove" class="approve-select">继续下一个审批</el-checkbox>
          </DialogTitle>
          <div v-if="operateData.approvalExplanation" :style="styConfig" :title="operateData.approvalExplanation" class="audit-tip">
            {{ operateData.approvalExplanation }}
          </div>
          <div :style="{maxHeight: maxHeight}" class="auditDialog-scroll">
            <el-form
              ref="projectForm"
              :model="projectForm"
              :style="showMobilePage?'':'padding-left: 12px; padding-right: 12px'"
              :label-width="showMobilePage? '80px': '120px'"
              label-position="right"
            >
              <!-- 必显示 非必填-->
              <el-form-item
                v-if="!content || (content && !content.isRichText)"
                :class="{'is-required': isRequiredText}"
                label="审批意见"
                prop="remark"
                class="form-textarea"
              >
                <el-input
                  ref="remarkRef"
                  v-model="projectForm.remark"
                  :rows="5"
                  :class="{width240: !showMobilePage}"
                  maxlength="200"
                  placeholder="审批意见"
                  type="textarea"
                  resize="none"
                  @blur="blur"
                />
              </el-form-item>
              <el-form-item v-else :label="''" prop="remark" class="form-rich-textarea">
                <!-- 富文本 -->
                <div class="flex">
                  <div v-if="isRequiredText" class="required-tag">*</div>
                  <RichEditor
                    v-if="dialogFormVisible"
                    ref="richEditorRef"
                    v-model="projectForm.remarkRichText"
                    :editor-height="170"
                  />
                </div>

              </el-form-item>
              <el-form-item label="快捷回复">
                <quickReply @selectText="selectText" />
              </el-form-item>
              <el-form-item label="附件">
                <upAttachment
                  ref="uploadImg"
                  :import-api="'/admin/contract/file/upload'"
                  :hide-confirm="true"
                  :is-disabled="false"
                  :file-list="projectForm.attachment"
                  :limit="10"
                  style="width: 240px;"
                  btn-text="上传附件"
                  class="field-upload"
                  @upLoadError="upLoadError"
                  @upProgress="upProgress"
                  @complateSetData="complateSetData"
                  @removeFileList="removeFileList"
                />
              </el-form-item>
              <div v-if="!type" :class="{'mobile-back': showMobilePage}" class="mb22">
                <el-select v-model="rejectType" size="small" placeholder="请选择" class="type-box" style="width: 120px" @change="selectType">
                  <el-option
                    v-for="item in rejectTypeData.options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                  />
                </el-select>
                <el-select v-if="rejectType" key="rejectType_1" v-model="refuseNodeIds" popper-class="global-select-down" class="option-box" multiple collapse-tags size="small" placeholder="请选择" style="width: 240px">
                  <el-option
                    v-for="nodeItem in rejectData.data"
                    :key="nodeItem.id"
                    :label="nodeItem.backNodeName"
                    :value="nodeItem.nodeId"
                  />
                </el-select>
                <el-select v-else key="rejectType_0" v-model="rejectStep" size="small" placeholder="请选择" class="option-box" style="width: 240px">
                  <el-option-group v-for="(rejectItem, rejectIndex) in rejectList" :key="rejectIndex">
                    <el-option
                      v-for="nodeItem in rejectItem.rejectOptions"
                      :key="nodeItem.nodeId"
                      :label="nodeItem.nodeName"
                      :value="nodeItem.nodeId"
                      :title="nodeItem.nodeName.length > 16 && nodeItem.nodeName"
                    />
                  </el-option-group>
                </el-select>
                <el-tooltip v-if="rejectType" placement="top" popper-class="radio-tip">
                  <div slot="content" style="max-width: 200px;">退回节点重新处理后，将会提交给你继续审批，退回节点可多选</div>
                  <tipIcon is-diy style="margin: -4px 0 0 4px;"/>
                </el-tooltip>
              </div>
            </el-form>
          </div>
          <div class="dialog-footer" style="display:flex;justify-content:center;">
            <template v-if="type">
              <SubmitBtnList ref="submitBtnListRef" :is-rich-text="!(!content || (content && !content.isRichText))" :default-aduitor-list="defaultAduitorList" :default-auth-user-list="defaultAuthUserList" :current-node-id="operateData.currentNodeId" :submit-btn-list="operateData.submitBtnList" :disabled="createLoading" :loading="loading" @onShow="onShow" @handleSubmit="handleSubmit" />
            </template>
            <div v-else class="btn-wrap">
              <el-button :loading="loading" type="primary" size="small" @click="handleSubmit">确定</el-button>
              <el-button class="cancel-btn-style" type="info" @click="handleClose">再想想</el-button>
            </div>
          </div>
      </div></template>
    </el-dialog>
  </div>
</template>
<script>
import RichEditor from '@/components/Editor/RichEditor';
import DialogTitle from '@/components/Title';
import upAttachment from '@/components/Common/upAttachment/index';
import quickReply from '@/components/AuditProcess/quickReply';
import { AutoFillUser } from '@/utils/aduitor';
import SubmitBtnList from './submitBtnList';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';

export default {
  components: {
    DialogTitle,
    RichEditor,
    upAttachment,
    SubmitBtnList,
    quickReply
  },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false
    },
    operateData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    createUser: { // 创建人
      type: Object,
      default: null
    },
    content: {
      type: Object,
      default: () => ({})
    },
    auditScheduleData: {
      type: Object,
      default: () => ({})
    },
    type: { // 0：拒绝 1：同意
      type: Number,
      default: null
    },
    loading: {
      type: Boolean,
      default: false
    },
    defaultAduitorList: { // 申请人
      type: Array,
      default: () => ([])
    },
    defaultAuthUserList: { // 授权人
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      projectForm: {
        remark: '',
        remarkRichText: '',
        attachment: []
      },
      remarkIndex: null, // 审批意见输入框光标位置
      editorInstance: null, // VueUeditorWrap实例
      createLoading: false,
      continueApprove: false,
      rejectStep: 'perStep', // 拒绝至节点
      refuseNodeIds: [],
      rejectList: [], // 拒绝节点
      maxHeight: '',
      rejectType: 0,
      rejectData: {
        data: []
      }
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage,
      'device': state => state.app.device
    }),
    isRequiredText() {
      return this.content &&
        ((this.type === 0 && this.content.isRejectRequired) ||
        (this.type === 1 && this.content.isPassedRequired));
    },
    defaultRejectList() {
      return [
        {
          rejectOptions: [
            { nodeId: 'perStep', nodeName: '上一步' },
            { nodeId: 'firstStep', nodeName: '任务发起' }
          ]
        }
      ];
    },
    styConfig() {
      if (!this.operateData.approvalExplanation || !this.operateData.approvalExplanationStyle) {
        return {};
      }
      const styConfig = this.operateData.approvalExplanationStyle ? JSON.parse(this.operateData.approvalExplanationStyle) : {};
      const obj = {
        backgroundColor: styConfig.bgColor,
        color: styConfig.color
      };
      return obj;
    },
    rejectTypeData() {
      return {
        options: [
          { value: 0, label: '退回整个流程', disabled: Boolean(this.operateData.designatedNode) },
          { value: 1, label: '退回指定节点', disabled: !hasRouteAuth('crm:contract:return') || this.rejectData.data.length === 0 }
        ]
      };
    }
  },

  watch: {
    continueApprove(val) {
      const continueApproveLocalKey = 'CONTINUE_APPROVE_' + this.userInfo.id;
      window.localStorage.setItem(continueApproveLocalKey, val);
    },
    auditScheduleData(data) {
      this.rejectList = JSON.parse(JSON.stringify(this.defaultRejectList));
      const rejectData = {
        rejectOptions: []
      };
      var temp = [];
      data.process.forEach((processItem, index) => {
        // 2.9.7 过滤任务发起节点和抄送节点
        // 3.3.0 过滤达人审批节点
        if (processItem.nodeStatus === 0 && index !== 0 && processItem.nodeType !== 3 && processItem.nodeType !== 4) {
          const nodeData = Object.create(null);
          nodeData.nodeId = processItem.id;
          nodeData.nodeName = '';
          processItem.examineRoles.forEach(roleItem => {
            nodeData.nodeName += (nodeData.nodeName && '/') + roleItem.roleName;
          });
          rejectData.rejectOptions.unshift(nodeData);
        }
      });
      // nodeStatus 0-已审批，1-审批中，2-未审批，未审批的节点不可以选择
      const tempProcess = data.process.filter(item => {
        return item.nodeType === 0 && item.nodeStatus !== 2;
      });
      tempProcess.forEach(item => {
        const res = item.examineRoles.filter(cur => {
          // 1-已提交，3-审批中，不是已提交(发起节点)和审批中的节点才可以退回
          return ![1, 3].includes(cur.status);
        });
        if (res.length > 0) {
          const node = {
            nodeId: item.id,
            backNodeName: res.map(ele => ele.roleName).join('/')
          };
          temp.push(node);
        }
        // v3.4.6新增发起人选项
        item.examineRoles.map(it => {
          if (it.roleType === 6) {
            const node = {
              nodeId: item.id,
              backNodeName: '发起人'
            };
            temp.push(node);
          }
        });
      });
      this.$set(this.rejectData, 'data', temp);
      if (rejectData.rejectOptions.length) this.rejectList.push(rejectData);
    },
    operateData(val) {
      this.backFill(val);
    }
  },
  created() {
    const continueApproveLocalKey = 'CONTINUE_APPROVE_' + this.userInfo.id;
    const getApproveLocalStatus = window.localStorage.getItem(continueApproveLocalKey);
    this.continueApprove = ![null, 'false'].includes(getApproveLocalStatus);
  },
  methods: {
    blur(e) {
      this.remarkIndex = e.srcElement.selectionStart;
    },
    onShow(item) {
      this.submitItem = item;
    },
    selectText(text) {
      if (!this.content || (this.content && !this.content.isRichText)) {
        const remark = this.projectForm.remark;
        this.projectForm.remark = remark.slice(0, this.remarkIndex) + text + remark.slice(this.remarkIndex);
      } else {
        this.$refs['richEditorRef'].insertText(text);
      }
    },
    ready(editorInstance) {
      this.editorInstance = editorInstance;
    },
    handleSubmit(_aduitors = null, buttonRoleId = null) {
      const formData = JSON.parse(JSON.stringify(this.projectForm));
      if (this.isRequiredText) {
        let text = (this.content && !this.content.isRichText) ? this.projectForm.remark : this.projectForm.remarkRichText;
        if (text === '<p><br></p>') {
          text = '';
        }
        if (!text) {
          ElMessage.error('请输入审批意见');
          return;
        }
      }
      if (this.type === 0) { // 审批拒绝
        if (this.rejectType) { // 退回至指定节点
          if (this.refuseNodeIds.length === 0) {
            ElMessage.warning('请选择退回指定的节点！');
            return;
          }
          formData.refuseNodeIds = this.refuseNodeIds.join(',');
        } else if (this.rejectType === 0) { // 退回至整个流程
          if (this.rejectStep === 'firstStep') {
            formData.backsponsor = true;
          } else if (this.rejectStep === 'perStep') {
            formData.backsponsor = false;
          } else {
            formData.backsponsor = false;
            formData.refuseToNodeId = this.rejectStep;
          }
        } else {
          ElMessage.warning('当前审批没有退回功能！');
          return;
        }
      } else if (_aduitors) {
        formData.aduitors = _aduitors;
      }
      if (buttonRoleId) {
        formData.buttonRoleId = buttonRoleId;
      }
      // 审批拒绝 && 选择退回指定节点，status 传递4，否则传递type值
      this.$emit('handleSubmit', (this.type === 0 && this.rejectType) ? 4 : this.type, formData);
    },
    handleClose() {
      this.rejectStep = 'perStep';
      this.resetForm();
      this.$emit('close');
    },
    opened() {
      const clientHeight = window.innerHeight;
      this.maxHeight = ((clientHeight * 4) / 5) - 142 + 'px';
      const createUser = this.createUser || this.userInfo;
      AutoFillUser(this.operateData.submitBtnList, createUser, this.defaultAduitorList[0], this.defaultAuthUserList[0]); // 自动回填用户
      this.rejectStep = 'perStep';
      this.resetForm();
      this.backFill(this.operateData);
    },
    backFill(val) {
      if (val.designatedNode) {
        this.rejectType = hasRouteAuth('crm:contract:return') ? 1 : null;
        this.rejectData.data && this.rejectData.data.length === 0 && (this.rejectType = null);
      } else {
        this.rejectType = 0;
      }
    },
    resetForm() {
      this.projectForm = {
        remark: '',
        remarkRichText: '',
        attachment: []
      };
      this.rejectType = '';
      this.refuseNodeIds = '';
    },
    upProgress() {
      this.createLoading = true;
    },
    complateSetData({ data, fileName }) {
      this.createLoading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      this.projectForm.attachment.push(fileList);
    },
    upLoadError() {
      this.createLoading = false;
    },
    removeFileList({ file, index }) {
      this.projectForm.attachment.splice(index, 1);
    },
    selectType(val) {
      if (val) {
        this.rejectStep = '';
        this.refuseNodeIds = [];
      } else {
        this.rejectStep = 'perStep';
      }
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-input__inner {
  max-width: 240px;
  display: inline-block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  padding-right: 16px;
}
::v-deep .el-tag {
  background-color: #eff3fb;
  color: #333;
  position: relative;
  &:first-of-type{
    padding-right: 20px;
  }
  .el-select__tags-text {
    display: inline-block;
    max-width: 120px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .el-tag__close {
    position: absolute;
    top: 3px;
    right: 0px;
    font-size: 16px;
    background-color: transparent;
    color: #333;
  }
}
.mb22 {
  margin-bottom: 22px;
}
.type-box {
  &::v-deep {
    .el-input__inner {
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }
    .el-input .el-input__inner {
      border-color: #DCDFE6;
    }
  }
}
.option-box {
  left: -5px;
  &::v-deep {
    .el-input__inner {
      border-left: none;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
    .el-input .el-input__inner {
      border-color: #DCDFE6;
    }
  }
}
.form-rich-textarea {
  margin-right: 0;
  & ::v-deep {
    .w-e-text-placeholder {
      top: 0 !important;
    }
    .el-form-item__content {
      margin-left: 0 !important;
    }
    .el-form-item__content {
      line-height: 1px;
    }
  }
}
.btn-wrap{
  display: flex;
  justify-content: center;
}
.audit-dialog {
  &::v-deep {
    .order-import-button .import-btn {
      width: 240px;
    }
    .small-common-dialog-size .el-dialog__body {
      padding-bottom: 16px !important;

    }
    .small-dialog-size {
      width: 30%;
    }
  }
}
.required-tag {
  margin-right: 8px;
  color: red;
}
.field-upload {
  &::v-deep {
    .file-container {
      max-height: 60px;
      overflow-y: auto;
    }
  }
}
.el-button--danger.is-plain{
  border-color: #F56C6C;
}
.approve-select {
  margin-left: 12px;
  ::v-deep .el-checkbox__label {
    padding-left: 4px;
    color: #666;
  }
}
.audit-tip {
  // display: flex;
  // align-items: center;
  background: #ffeff0;
  border-radius: 2px;
  padding: 8px 12px;
  margin-bottom: 9px;
  font-size: 12px;
  color: #FF4E5F;
  line-height: 1.2;

  overflow : hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 6;
  -webkit-box-orient: vertical;
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-textarea__inner {
      width: 240px;
    }
  }
}
.mobile-page-dialog {
  &::v-deep {
    .el-dialog {
      width: 100% !important;
      .el-dialog__close {
        right: -5px !important;
        top: -52px !important;
      }
    }
    .textbus-form-body {
      max-height: 123px !important;
      min-width: 100%;
    }
    .dialog-footer {
      margin-top: 10px;
    }
  }
  .auditDialog-scroll {
    @include scrollBar($x: unset, $y: unset);
  }
}
.auditDialog-scroll {
  @include scrollBar($x: hidden, $y: auto, $width: 6px);
}
.mobile-back {
  display: flex;
  align-items: center;
  .option-box {
    flex: 1;
  }
}
</style>
<style lang="scss">
textarea#editor-id-01 {
  display: none;
}
</style>
